﻿/**
 * Mapper
 *
 * @author		Allen Chou
 * @version		1.0.1 (last update: Apr 27 2008)
 * @link		http://cjcat2266.deviantart.com
 */

package idv.cjcat.utils.mapper {
	import flash.display.*;
	import flash.events.*;
	import flash.errors.*;
	
	public class Mapper {
		
		private static var _initiated:Boolean = false;
		private static var _stage:Stage;
		
		private var _autoRefresh:Boolean;
		private var _trackerPairs:Array = new Array();
		
		public static function init(stage:Stage):void {
			if (!_initiated) _stage = stage;
			_initiated = true;
		}
		
		public function Mapper(autoRefresh:Boolean = true):void {
			if (!_initiated) throw new IllegalOperationError("call Mapper.init(stage) first.");
			this.autoRefresh = autoRefresh;
		}
		
		public function addTracker(tracker:Object, property:String, target:Object, targetProperty:String = "", factor:Number = 1, offset:Number = 0, preoffset:Number = 0):void {
			if (targetProperty == "") targetProperty = property;
			for (var i:int = 0; i < _trackerPairs.length; i++) {
				if ((tracker  == _trackerPairs[i].tracker ) &&
					(property == _trackerPairs[i].property)    ) {
						
						_trackerPairs.splice(i, 1);
						break;
				}
			}
			_trackerPairs.push(new TrackerPair(tracker, property, target, targetProperty, factor, offset, preoffset));
		}
		
		public function changeRelation(tracker:Object, property:String, factor:Number = 1, offset:Number = 0, preoffset:Number = 0):void {
			
			var pair:TrackerPair;
			for (var i:int = 0; i < _trackerPairs.length; i++) {
				pair = _trackerPairs[i] as TrackerPair;
				if ((tracker  == pair.tracker ) &&
					(property == pair.property)    ) {
						
						pair.factor = factor;
						pair.offset = offset;
						pair.preoffset = preoffset;
						return;
				}
			}
		}
		
		public function removeTracker(tracker:Object, property:String):void {
			
			var pair:TrackerPair;
			for (var i:int = 0; i < _trackerPairs.length; i++) {
				pair = _trackerPairs[i] as TrackerPair;
				if ((tracker  == pair.tracker ) &&
					(property == pair.property)    ) {
						
						_trackerPairs.splice(i, 1);
						return;
				}
			}
		}
		
		public function get autoRefresh():Boolean {
			return _autoRefresh;
		}
		
		public function set autoRefresh(value:Boolean):void {
			_autoRefresh = value;
			
			if (_autoRefresh) {
				_stage.addEventListener(Event.ENTER_FRAME, refresh);
			} else {
				_stage.removeEventListener(Event.ENTER_FRAME, refresh);
			}
		}
		
		public function refresh(e:Event):void {
			
			var pair:TrackerPair
			for (var i:int = 0; i < _trackerPairs.length; i++) {
				pair = _trackerPairs[i] as TrackerPair;
				pair.tracker[pair.property] = (pair.target[pair.targetProperty] + pair.preoffset) * pair.factor + pair.offset;
			}
		}
		
	}
	
}